﻿using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace 自引用的组织结构树
{
    internal class Program
    {
        static void Main(string[] args)
        {
            /*OrgUnit orgUnit = new OrgUnit() { Name = "子正集团" };

            OrgUnit orgUnit1 = new OrgUnit() { Name = "子正集团亚洲区" };
            orgUnit1.Parent = orgUnit;

            OrgUnit orgUnitz = new OrgUnit() { Name = "子正集团中国" };
            orgUnitz.Parent = orgUnit1;
            OrgUnit orgUnits = new OrgUnit() { Name = "子正集团新加坡" };
            orgUnits.Parent = orgUnit1;

            OrgUnit orgUnit2 = new OrgUnit() { Name = "子正集团北美区" };
            orgUnit2.Parent = orgUnit;

            OrgUnit orgUnitus = new OrgUnit() { Name = "子正集团美国" };
            orgUnitus.Parent = orgUnit2;
            OrgUnit orgUnitca = new OrgUnit() { Name = "子正集团加拿大" };
            orgUnitca.Parent = orgUnit2;*/

            using (MyDbContext ctx = new MyDbContext())
            {
                /*ctx.OrgUnits.Add(orgUnit);
                ctx.OrgUnits.Add(orgUnit1);
                ctx.OrgUnits.Add(orgUnitz);
                ctx.OrgUnits.Add(orgUnits);
                ctx.OrgUnits.Add(orgUnit2);
                ctx.OrgUnits.Add(orgUnitus);
                ctx.OrgUnits.Add(orgUnitca);
                ctx.SaveChanges();*/
                //var u = ctx.OrgUnits.Single(o => o.Parent == null);
                PrintChildren(0, ctx);
            }
        }

        static void PrintChildren(int indentLevel, MyDbContext ctx, OrgUnit? parent = null)
        {
            var Children = ctx.OrgUnits.Where(o => o.Parent == parent).ToList();
            foreach (var item in Children)
            {
                Console.Write(new string('+', indentLevel));//输出缩进
                Console.WriteLine(item.Name);
                PrintChildren(indentLevel + 1, ctx, item);
            }
        }

    }
}
